package wsi.gui.function.select;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;

import org.rygh.core.model.notice.NotificationCenter;
import org.rygh.gui.swing.common.window.SInfoWindow;
import org.rygh.gui.swing.presenter.CallbackSPresenter;
import org.rygh.gui.swing.tree.STreeNode;
import org.rygh.gui.swing.tree.STreeView;

import wsi.function.Function;
import wsi.gui.Property;

public class FunctionSelectPresenter extends CallbackSPresenter<Function> {
	public interface Display extends CallbackSPresenter.Display {

		STreeView getTree();
	}

	public final static String EVENT_REFRESH_FUNCTIONS = "EVENT_REFRESH_FUNCTIONS";

	private final FunctionRoot root = new FunctionRoot();

	public FunctionSelectPresenter() {
		display = new FunctionSelectWindow(this);

		bind();
	}

	@Override
	protected void bind() {
		super.bind();

		final Display d = (Display) display;

		d.getTree().addTreeSelectionListener(new TreeSelectionListener() {
			@Override
			public void valueChanged(TreeSelectionEvent e) {
				if (d.getTree().getLastSelectedPathComponent() == null)
					return;

				STreeNode<?> node = (STreeNode<?>) d.getTree()
						.getLastSelectedPathComponent();

				setValue((Function) node.getValue());
			}
		});

		d.getTree().addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (d.getTree().getLastSelectedPathComponent() == null)
					return;

				STreeNode<?> node = (STreeNode<?>) d.getTree()
						.getLastSelectedPathComponent();

				if (!node.isLeaf())
					return;

				if (e.getClickCount() == 2)
					close();
			}
		});

		refresh();
	}

	@Override
	public void close() {
		Property.shared().recordFunction(getValue());
		super.close();
	}

	public void refresh() {
		root.load();

		final Display d = (Display) display;
		d.getTree().setModel(root.getModel());
		d.getTree().expandAll();
		d.getTree().filter();

		NotificationCenter.shared().post(EVENT_REFRESH_FUNCTIONS, null);
		SInfoWindow.display(getWindow().getTitle(), "Functions reloaded.");
	}

}
